﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class DepartmentController : BaseController
    {
        private readonly ILogger<DepartmentController> _logger;
        public DepartmentController(ILogger<DepartmentController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] long pid)
        {
            List<Department> departments = await _fsql.Select<Department>().Where(d => d.Pid == pid).ToListAsync();
            _logger.LogInformation(_fsql.Select<Department>().Where(d => d.Pid == pid).ToSql());
            return RenderJson(data: departments);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> GetAll([FromForm] long pid)
        {
            JArray data = getMenuTreeData(0).Result;
            return RenderJson(data: data);
        }

        [NonAction]
        public async Task<JArray> getMenuTreeData(long pid)
        {
            JArray data = new JArray();
            List<Department> departments = await _fsql.Select<Department>().Where(m => m.Pid == pid).ToListAsync();
            if (departments != null && departments.Count > 0)
            {
                foreach (var department in departments)
                {
                    JObject jo_menu = JObject.FromObject(department);
                    jo_menu.Add("children", getMenuTreeData(department.Id).Result);
                    data.Add(jo_menu);
                }
            }
            return data;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> GetAllParentId([FromForm] long id)
        {
            JArray data = getParentIdData(id).Result;
            return RenderJson(data: data);
        }

        private JArray ja_parent_ids = new();
        [NonAction]
        public async Task<JArray> getParentIdData(long id)
        {
            long pid = await _fsql.Select<Department>().Where(m => m.Id == id).ToOneAsync(dp => dp.Pid);
            ja_parent_ids.Add(id);
            if (pid != 0)
            {
                await getParentIdData(pid);
            }
            return ja_parent_ids;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] Department department)
        {
            #region 将来可能需要
            //string status = "failed";
            //string message = "该部门已存在";
            //int code = -1;
            //// 判断用户是否存在
            //Department isExistsUser = await _fsql.Select<Department>().Where(d => d.Name == department.Name).ToOneAsync();
            //if (isExistsUser == null)
            //{
            //    long id = await _fsql.Insert(department).ExecuteIdentityAsync();
            //    department.Id = id;
            //    status = "success";
            //    message = "添加部门成功";
            //    code = 0;
            //}
            //return RenderJson(status: status, message: message, code: code, data: department);
            #endregion
            long id = await _fsql.Insert(department).ExecuteIdentityAsync();
            department.Id = id;
            return RenderJson(data: department);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = -1;
            _fsql.Transaction(() => {
                // 删除部门和员工对应关系
                affrows = _fsql.Delete<DepartmentUser>().Where(dptu => dptu.Dpid == id).ExecuteAffrows();
                // 删除部门和权限对应关系
                affrows = _fsql.Delete<DepartmentPermission>().Where(dptp => dptp.Dpid == id).ExecuteAffrows();

                affrows = _fsql.Delete<Department>().Where(d => d.Id == id).ExecuteAffrows();
            });
            
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] Department department) {
            int affrows = await _fsql.Update<Department>().SetSourceIgnore(department, colval => colval == null).ExecuteAffrowsAsync();
            _logger.LogInformation("部门更新：" + _fsql.Update<Department>().SetSourceIgnore(department, colval => colval == null).ToSql());
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            Department department = await _fsql.Select<Department>().Where(d => d.Id == id).ToOneAsync();
            return RenderJson(data: department);
        }
    }
}
